package handler

import (
	"commerce/api/request"
	"commerce/global"
	"commerce/interal/dao"
	"commerce/interal/model"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"net/http"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{}, &user)
	if user.Mobile == req.Mobile {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此用户已存在",
			"data": nil,
		})
		return
	}
	user = model.Users{
		Mobile:   req.Mobile,
		PassWord: req.Password,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": user,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.PassWord != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, err := jwt.NewJWT(global.JWT_KEY).CreateToken(jwt.CustomClaims{ID: uint(user.Id)})
	if err != nil {
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": token,
	})
}
